﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace SPQueryToSql.ApplicationObjects.CAML
{
    internal class ViewFields
    {
        public List<FieldRef> Fields;

        public ViewFields(XContainer element, IEnumerable<FieldInfo> listFields)
        {
            Fields = new List<FieldRef>();
            foreach (var child in element.Elements())
            {
                var field = new FieldRef(child);
                var listField = listFields
                    .FirstOrDefault(f => f.Id == field.ID || f.InternalName == field.Name);
                if (listField != null)
                {
                    field.Name = listField.InternalName;
                    field.ID = listField.Id;
                }
                Fields.Add(field);
            }
        }

        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.Append("<ViewFields>");
            sb.Append(Environment.NewLine);
            foreach (var field in Fields)
            {
                sb.Append("\t");
                sb.Append(field.ToString());
            }
            sb.Append("</ViewFields>");
            return sb.ToString();
        }
    }
}
